package com.project.controller;

import com.project.util.CheckUtil;
import com.project.util.WechatToXml;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/acl")
public class WX {


    /**
     *  暴露给微信的接口  并初始化公众号菜单
     *  获取关注人信息
     * @param request
     * @param response
     */
    @RequestMapping(value = "/follow", produces = "text/html;charset=UTF-8")
    public void follow(HttpServletRequest request, HttpServletResponse response)throws  Exception{
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        //获取微信返回数据的提交方式
        Boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        print = response.getWriter();
        if (isGet){
            //微信签名
            String signature = request.getParameter("signature");
            //时间戳
            String  timestamp = request.getParameter("timestamp");
            //随机数
            String  nonce  = request.getParameter("nonce");
            //随机字符串
            String echostr  = request.getParameter("echostr");



            String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && CheckUtil.checkSignature(signature,timestamp,nonce)){
                try {
                    print.write(echostr);
                    print.flush();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else{//不是Get方式
            //封装参数
            Map<String,String> map = WechatToXml.xmlToMap(request);

            for (String s: map.keySet()) {
                System.out.println(s+"    :    "+map.get(s));
            }
            //事件类型
            String event = map.get("Event");
            //开发者微信号
            String ToUserName = map.get("ToUserName");
            //openid
            String FromUserName = map.get("FromUserName");

            //判断是什么事件
            if (event.equals("subscribe")){//关注事件
                String message = WechatToXml.textMsg(ToUserName,FromUserName,"你好！！！！！！！！！！");
                print.write(message);
                print.flush();
            }
        }

    }

}
